package cn.windfly.don.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceException;

import cn.windfly.don.Constant;
import cn.windfly.don.pojo.JsonResult;
import cn.windfly.util.JsonUtil;
import cn.windfly.util.LogUtil;
import cn.windfly.util.exception.MessageException;

/**
 * ，以及异常处理
 * <p>
 * 在业务处理逻辑抛出异常时，捕获异常并构造返回错误json值
 * 
 * @author DFH
 * 
 */
@WebFilter(urlPatterns = "*")
public class ErrorFilter implements Filter {

	/**
	 * 暂不处理
	 */
	@Override
	public void destroy() {

	}

	/**
	 * 过滤逻辑，捕获到异常也返回错误JSON格式
	 */
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		String result = null;
		HttpServletRequest request = (HttpServletRequest) arg0;
		String header = request.getHeader("Accept");
		HttpServletResponse response = (HttpServletResponse) arg1;
		response.setCharacterEncoding("UTF-8");
		String header2 = request.getHeader("Content-Type");
		String header3 = response.getHeader("Content-Type");
		
		try {
			arg2.doFilter(arg0, arg1);
			if (response.getStatus() == 404) {
			}
		} catch (ServletException e) { // 调用异常
			
			
			if (!((header != null && header.contains("json")) || (header2 != null && header2.contains("json"))
					|| (header3 != null && header3.contains("json")))) {
				//e.printStackTrace();
				LogUtil.error(e);
				result = JsonUtil.toJson(JsonResult.newErrorResult(Constant.SERVER_ERROR_MSG));
			}else {
				Throwable cause = e.getRootCause();
				e.printStackTrace();
				// 由于框架使用反射机制，先判断是否是反射内部的异常
				if (cause instanceof java.lang.reflect.InvocationTargetException) {
					Throwable cause2 = cause.getCause();
					// 是否为webservice调用异常
					if (cause2 instanceof WebServiceException) {
						LogUtil.error(e);
						result = JsonUtil.toJson(JsonResult.newErrorResult(Constant.SERVER_ERROR_MSG));
					} else if (cause2 instanceof MessageException) {
						result = JsonUtil.toJson(JsonResult.newErrorResult(cause2.getMessage()));
					} else {
						LogUtil.error(e);
						result = JsonUtil.toJson(JsonResult.newErrorResult(Constant.SERVER_ERROR_MSG));
					}
				} else {
					LogUtil.error(e);
					result = JsonUtil.toJson(JsonResult.newErrorResult(Constant.SERVER_ERROR_MSG));
				}
			}

		} catch (Exception e) { // 其他异常
			LogUtil.error(e);
			result = JsonUtil.toJson(JsonResult.newErrorResult(Constant.SERVER_ERROR_MSG));
		}
		if (result != null) {
			if(request.getHeader("User-Agent").contains("MSIE") || request.getHeader("User-Agent").contains("rv:11")){
				response.setContentType("text/html;charset=UTF-8");
			}else {
				response.setContentType("application/json;charset=UTF-8");
			}
			arg1.getWriter().write(result);
			arg1.getWriter().flush();
		}

	}

	/**
	 * 初始化
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
